package swing.admin.test;

import javax.swing.*;
import java.awt.*;
import java.util.Arrays;

public class ChartFrame extends JFrame {

    public ChartFrame() throws HeadlessException {
        mainPanel mainPanel = new mainPanel();
        mainPanel.setBackground(Color.WHITE);
        add(mainPanel);
    }

    public static void main(String[] args) {
        ChartFrame frame = new ChartFrame();
        frame.setTitle("条形统计图");
        frame.setSize(800, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    class mainPanel extends JPanel {

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setFont(new Font("Times", Font.PLAIN, 14));

            int MAX_HEIGHT = getHeight() - 100;
            int MAX_WIDTH = getWidth();


            int[] data = {2, 5, 13, 7, 14};
            int total = Arrays.stream(data).sum();

            for (int i = 0; i < data.length; i++) {
                int height = (int) ((((float) data[i]) / total) * MAX_HEIGHT);
                int x = 10 + 30 * i;
                int y = MAX_HEIGHT - height;

                g.setColor(new Color(78, 81, 87));
                g.fillRect(x, y, 20, height + 10);

                g.setColor(Color.BLACK);
                g.drawString(String.valueOf(data[i]), x, y - 10);
                g.drawString(String.valueOf(i), x, MAX_HEIGHT + 30);
            }

            g.drawLine(10, MAX_HEIGHT + 10, MAX_WIDTH - 10, MAX_HEIGHT + 10);

        }
    }
}
